package com.james.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：zhz
 * @date ：2022/7/3 17:48
 * @description：TODO
 * @version: 1.0
 */
//@Component
@Order(99)
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("hello filter");
        if(servletRequest.getAttribute("token") == null){
            returnNoLogin((HttpServletResponse) servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private void returnNoLogin(HttpServletResponse servletResponse) throws IOException {
        HttpServletResponse response = servletResponse;
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "登录失败，请登录!");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(jsonObject));
    }

}
